import {Component} from 'react';
import {connect} from 'react-redux';
import axios from 'axios';
import * as Notification from 'modules/notification/actions';
import Session from 'modules/auth/session';
import {Button, PageHeader} from 'antd';
import { Modal , Input} from 'antd';
import styled from "styled-components";
import {func} from "prop-types";

const Outer = styled.div`
  border:1px solid #ececec;
  margin:20px;
  
   box-shadow: 3px 3px 6px rgba(0,0,0,0.1), 3px 3px 6px rgba(0,0,0,0.2);
`;

const Title = styled.div`
  background:#f1f1f1;
  height:50px;
  line-height:50px;
  text-indent:1em;
  color:#333;
  font-weight: bold;
`;

const Conten = styled.div`
  margin:20px;
  box-sizing:border-box;
`;

const Item = styled.div`
  display:flex;
  width:49%;
  margin:10px 0;
  float: left;
`;
const Bold = styled.span`
  font-weight:bold;
`;
const Clear = styled.span`
  clear:both;
      display: block;
    height: 0;
`;
const Inline = styled.span`
  display: inline-block;
    word-break: break-all;
    width: calc( 100% - 130px );
`;
const CenterBtn = styled.div`
  text-align:center;
  padding:20px
`;

class Collection extends Component {
    state = {
        search: '',
        document: {
            action: '',
            visible: false,
            dimmed: false
        },
        confirm: {
            visible: false,
            imsi: ''
        },
        view: {
            visible: false,
            disableOnClickOutside: false,
            imsi: ''
        },
        listData: [],
        visible: false,
        times:'30',
        waitTimes:30,
        showLoad:false
    };

    componentWillMount() {

        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/equipmentinfo',
            params: {},
            // data
        }).then(res => {

            $this.setState({
                    listData: res.data[0].listData
                }
            )

        })
    }

    getSData() {
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/equipmentinfo',
            params: {},
            // data
        }).then(res => {
            this.setState({
                    listData: res.data[0].listData
                }
            )
            dispatch(Notification.success({
                title: '提示',
                message: `设备信息加载成功！`
            }));
        })
    }

    getByShell(times) {
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }
        this.setState({
            waitTimes:times,
            showLoad:true
        });
         this.waitGetFile(times)
        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/shellAction',
            params: {
                time:times
            },
            // data
        }).then(res => {
            const getData = res.data
           
        })
    }
    getFile(){
        const {dispatch} = this.props
        window.open('/static/file/Wireshark.pcap')
    }
    waitGetFile(times){
        var $this=this
        var getTime=this.state.waitTimes
        var ins=0

        function waitT(){
            if(getTime <=0){
                clearInterval(ins)
                $this.setState({
                    showLoad:false
                });
                $this.getFile()
            }else{
                getTime--
                $this.setState({
                    waitTimes:getTime
                });
            }
        }
        setTimeout(function () {
            ins=setInterval(function () {
                waitT()
            },1000)
        },1000)
    }

    getByStopShell(){
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/shellActionStop',
            params: {},
            // data
        }).then(res => {
            const getData = res.data

            dispatch(Notification.info({
                title: '终止抓包结果',
                autoDismiss: 5,
                message: getData
            }));
        })
    }
    showModal = () => {
        this.setState({
            visible: true,
            times:'30'
        });
    };

    handleOk = e => {
        var getTime=this.state.times
        this.setState({
            visible: false,
        });
        let getTimes=isNaN(parseInt(getTime))?30:parseInt(getTime)
        if(getTimes<=0)getTimes=30
        this.getByShell(getTimes)
    };
    _handleChange(e) {
        let value = e.target.value;
        this.setState({
            times: value
        })
    }
    handleCancel = e => {
        this.setState({
            visible: false,
        });
    };
    render() {
        let $this = this
        const textArra = ['未启动', '运行正常']
        const textArraMore = ['断开', '建链成功']
        const Equipment_infoList = this.state.listData.map((ic, index) =>
            <Item key={index}><Bold>{ic.name == 'NG'?'NG接口':ic.name}：</Bold> <Inline>{index >= 12 ? (ic.name == 'NG'?(textArraMore[ic.value]):(textArra[ic.value])) : ic.value} </Inline>
            </Item>
        );
        return (
            <div>
                <PageHeader
                    style={{
                        border: '1px solid rgb(235, 237, 240)',
                    }}
                    title="设备信息"
                />
                <Outer>
                    <Conten>
                        {Equipment_infoList}
                        <Clear></Clear>
                    </Conten>
                </Outer>
                <CenterBtn>
                    <Button type="primary" onClick={() => this.getSData()}>刷新</Button>
                    {/*<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>*/}
                    {/*<Button type="primary" ghost onClick={() => this.showModal()}>一键抓包</Button>*/}
                    {/*<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>*/}
                    {/*<Button type="primary" ghost onClick={() => this.getByStopShell()}>终止抓包</Button>*/}
                </CenterBtn>
                {/*<Modal*/}
                {/*    title="请设置抓包时间（默认30秒）"*/}
                {/*    visible={this.state.visible}*/}
                {/*    onOk={this.handleOk}*/}
                {/*    okText={'确定'}*/}
                {/*    cancelText={'取消'}*/}
                {/*    onCancel={this.handleCancel}*/}
                {/*>*/}
                {/*    <Input type={'number'} addonAfter="秒" onChange={(e) => this._handleChange(e)} value={this.state.times} />*/}

                {/*</Modal>*/}
                {/*<div style={{*/}
                {/*    position:'fixed',*/}
                {/*    zIndex:'999',*/}
                {/*    top:0,*/}
                {/*    left:0,*/}
                {/*    background:'rgba(0,0,0,.3',*/}
                {/*    width:'100vw',*/}
                {/*    height:'100vh',*/}
                {/*    color:'#fff',*/}
                {/*    display:this.state.showLoad? 'flex' :'none',*/}
                {/*    justifyContent: 'center',*/}
                {/*    alignItems: 'center',*/}
                {/*    fontSize: '36px',*/}
                {/*    fontWeight: 'bold'*/}
                {/*}}>*/}
                {/*    <div>*/}
                {/*        <p>抓包中，请耐心等待!</p>*/}
                {/*        <p>倒计时：{this.state.waitTimes}秒</p>*/}
                {/*    </div>*/}
                {/*</div>*/}
            </div>
        )
    }
}

Collection = connect(
    (state) => ({})
)(Collection);

export default Collection;